import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qyou_app/common/api.dart';
import 'package:qyou_app/common/base.dart';
import 'package:qyou_app/common/bloc.dart';
import 'package:qyou_app/model/channel.dart';
import 'package:qyou_app/page/portal/home/carousel.dart';
import 'package:qyou_app/page/portal/home/video.dart';
import 'package:qyou_app/widget/refresh.dart';
import 'package:qyou_app/widget/setting.dart';

import '../header.dart';

class HomePage extends StatefulWidget {
  final _scrollController;
  HomePage(this._scrollController);

  @override
  State<StatefulWidget> createState() => _HomePageState(_scrollController);
}

class _HomePageState extends State<HomePage>
    with Base, AutomaticKeepAliveClientMixin {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  final _scrollController;
  _HomePageState(this._scrollController);

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  //下拉刷新，设置视频加载第一页，将获取的视频数据通知出去
  void _onRefresh() async {
    //1-删除缓存数据
    //2-获取视频数据
    //设置第一页
    BlocProvider.of<VideoPageNoCubit>(context).reset();
    List videoList = await Api.getVideoListData(context, 1);
    BlocProvider.of<VideoCubit>(context).updateVideoData(videoList);
    _refreshController.refreshCompleted();
  }

  //上拉加载
  void _onLoading() async {
    //获取之前加载的数据
    List videoData = BlocProvider.of<VideoCubit>(context).state;
    List videoList = await Api.getVideoListData(context);
    videoData.addAll(videoList);
    BlocProvider.of<VideoCubit>(context).updateVideoData(videoData);
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocBuilder<NavCubit, List<Channel>>(
        builder: (context, nav) => nav.length == 0
            ? null
            : DefaultTabController(
                length: nav.length,
                child: NestedScrollView(
                    controller: _scrollController,
                    headerSliverBuilder: (context, innerScrolled) => <Widget>[
                      SliverAppBar(
                        backgroundColor: Base.defaultColor,
                        brightness: Brightness.dark,
                        pinned: true,
                        floating: true,
                        snap: true,
                        expandedHeight: dp(55) + 49,
                        actions: <Widget>[
                          Header(
                            decoration: BoxDecoration(
                              color: Colors.transparent,
                            ),
                          ),
                        ],
                        flexibleSpace: FlexibleSpaceBar(  // 下拉渐入背景
                          background: Container(
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                begin: FractionalOffset.centerLeft,
                                end: FractionalOffset.centerRight,
                                colors: <Color>[
                                  Base.defaultColor,
                                  Base.defaultColor
                                ],
                              ),
                            ),
                          ),
                        ),
                        bottom: TabBar(
                          indicator: BoxDecoration(),
                          isScrollable: true,
                          //设置tab文字得类型
                          unselectedLabelStyle: TextStyle(
                            fontSize: 15,
                          ),
                          labelStyle: TextStyle(
                            fontSize: 18,
                          ),
                          //设置tab选中得颜色
                          labelColor: Colors.white,
                          //设置tab未选中得颜色
                          unselectedLabelColor: Colors.white70,
                          //设置自定义tab的指示器，CustomUnderlineTabIndicator
                          //若不需要自定义，可直接通过
                          // indicatorColor: Colors.white,  // 设置指示器颜色
                          indicatorWeight: 3,  // 设置指示器厚度
                          //indicatorPadding
                          //indicatorSize  设置指示器大小计算方式
                          ///指示器大小计算方式，TabBarIndicatorSize.label跟文字等宽,TabBarIndicatorSize.tab跟每个tab等宽
                          // indicatorSize: TabBarIndicatorSize.label,
                          tabs: nav.map((e) => Tab(text: e.name)).toList(),
                        ),
                        forceElevated: innerScrolled,
                      ),
                    ],
                    body: TabBarView(
                      children: nav.asMap().map((i, tab) => MapEntry(i, Builder(
                        builder: (context) => Container(
                          color: Colors.white,
                          child: ScrollConfiguration(
                            behavior: BehaviorNull(),
                            child: RefreshConfiguration(
                              headerTriggerDistance: dp(80),
                              maxOverScrollExtent : dp(100),
                              footerTriggerDistance: dp(50),
                              maxUnderScrollExtent: 0,
                              headerBuilder: () => MaterialClassicHeader(),
                              footerBuilder: () => ClassicFooter(),
                              child: SmartRefresher(
                                enablePullDown: true,
                                enablePullUp: true,
                                footer: RefreshFooter(bgColor: Color(0xfff1f5f6),),
                                controller: _refreshController,
                                onRefresh: _onRefresh,
                                onLoading: _onLoading,
                                child: CustomScrollView(
                                  // physics: BouncingScrollPhysics(),
                                  slivers: <Widget>[
                                    SliverToBoxAdapter(
                                      child: Container(
                                        child: i == 0 ? Column(
                                          children: [
                                            CarouselPage(),
                                            VideoPage(),
                                            //CateList(),
                                            //BroadcastSwiper(),
                                            //LiveList(),
                                          ],
                                        ) : null,
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),),
                      ).values.toList(),
                    ),
                ),
              ),
      ),
    );
  }
}
